<template>
    <div class="add-role">
        <!-- 页面头部区域 -->
        <header class="add-header">
            <div class="left">
                <!-- 返回按钮 -->
                <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
                <span>|</span>
                <!-- 动态显示标题：添加角色/编辑角色 -->
                <span>{{ title }}</span>
            </div>
            <div class="right">
                黑马程序员
            </div>
        </header>

        <!-- 页面主体内容区域 -->
        <main class="add-main">
            <div class="step-container">
                <!-- 左侧步骤条，用于显示当前操作进度 -->
                <el-steps direction="vertical" :active="activeStep">
                    <el-step title="角色信息" />
                    <el-step title="权限信息" />
                    <el-step title="检查并完成" />
                </el-steps>
            </div>

            <!-- 第一步：角色基本信息表单 -->
            <div v-show="activeStep === 1" class="form-container">
                <div class="form">
                    <el-form class="form-box" ref="roleForm" :model="roleForm" :rules="roleRules">
                        <el-form-item label="角色名称" prop="roleName">
                            <el-input v-model="roleForm.roleName" />
                        </el-form-item>

                        <el-form-item label="角色描述">
                            <el-input v-model="roleForm.remark" />
                        </el-form-item>

                    </el-form>

                </div>

            </div>

            <!-- 第二步：权限分配树形控件 -->
            <div v-show="activeStep === 2" class="form-container">
                <div class="tree-wrapper">
                    <div v-for="item in treeList" :key="item.id" class="tree-item">
                        <div class="tree-title">{{ item.title }}</div>

                        <el-tree ref="tree" :data="item.children" show-checkbox default-expand-all node-key="id"
                            highlight-current :props="{ label: 'title' }" check-strictly />
                    </div>

                </div>

            </div>

            <!-- 第三步：信息确认页面 -->
            <div v-show="activeStep === 3" class="form-container">
                <div class="title">检查并完成</div>
                <div class="form">
                    <div class="info">
                        <div class="form-item">角色名称：{{ roleForm.roleName }}</div>

                        <div class="form-item">角色描述：{{ roleForm.remark }}</div>

                        <div class="form-item">角色权限：</div>

                        <div class="tree-wrapper">
                            <div v-for="item in disableTreeList" :key="item.id" class="tree-item">
                                <div class="tree-title">{{ item.title }}</div>

                                <el-tree class="my-disabled" ref="diabledTree" :data="item.children" show-checkbox
                                    default-expand-all node-key="id" :highlight-current="false"
                                    :props="{ label: 'title' }" />
                            </div>

                        </div>

                    </div>

                </div>

            </div>

        </main>

        <!-- 页面底部操作按钮区域 -->
        <footer class="add-footer">
            <div class="btn-container">
                <el-button v-if="activeStep > 1" @click="decreseStep">上一步</el-button>

                <el-button v-if="activeStep < 3" type="primary" @click="increseStep">下一步</el-button>

                <el-button v-if="activeStep === 3" type="primary" @click="confirmAdd">{{ operat }}</el-button>

            </div>

        </footer>

    </div>

</template>

<script>
import { getTreeListAPI, createRoleUserAPI, getRoleDetailAPI, updateRoleAPI } from "@/api/system";

/**
 * 递归处理树形数据，添加disabled属性
 * @param {Array} treeList - 树形数据列表
 */
export function addDisabled(treeList) {
    treeList.forEach(item => {
        item.disabled = true
        // 如果有子节点，递归处理子节点
        if (item.children && item.children.length > 0) {
            addDisabled(item.children)
        }
    })
}

export default {
    data() {
        return {
            activeStep: 1, // 当前激活的步骤，默认第一步
            roleForm: {
                roleName: '', // 角色名称
                remark: '', // 角色描述
                perms: [], // 权限列表，二维数组格式
            },
            // 表单验证规则
            roleRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' }
                ]
            },
            treeList: [], // 权限树形数据
            disableTreeList: [], // 用于第三步展示的禁用状态树形数据
        }
    },

    computed: {
        // 从路由参数中获取角色ID
        roleId() {
            return this.$route.query.id
        },
        // 根据是否有roleId判断页面标题
        title() {
            return this.roleId ? '编辑角色' : '添加角色'
        },
        // 根据是否有roleId判断操作按钮文本
        operat() {
            return this.roleId ? '确认修改' : '确认添加'
        }
    },

    mounted() {
        // 组件挂载时获取权限树形数据
        this.getTreeList()
        // 如果是编辑模式，获取角色详情
        if (this.$route.query.id) {
            this.getRoleDetail()
        }
    },

    methods: {
        // 获取角色详情并回填数据
        async getRoleDetail() {
            const res = await getRoleDetailAPI(this.roleId)
            const { perms, remark, roleId, roleName } = res.data
            // 回填基础表单数据
            this.roleForm = { perms, remark, roleId, roleName }
            // 回填权限树选中状态
            this.$refs.tree.forEach((tree, index) => {
                tree.setCheckedKeys(this.roleForm.perms[index])
            })
        },

        // 返回上一步
        decreseStep() {
            if (this.activeStep === 1) return
            this.activeStep--
        },

        // 进入下一步
        increseStep() {
            if (this.activeStep === 3) return

            // 第一步：表单验证
            if (this.activeStep === 1) {
                this.$refs.roleForm.validate(valid => {
                    if (valid) {
                        this.activeStep++
                    }
                })
            }
            // 第二步：收集权限数据
            else if (this.activeStep === 2) {
                this.roleForm.perms = []
                // 获取每个树形控件选中的节点ID
                this.$refs.tree.forEach(tree => {
                    const arr = tree.getCheckedKeys()
                    this.roleForm.perms.push(arr)
                })

                // 验证是否选择了权限
                if (this.roleForm.perms.flat().length === 0) {
                    this.$message({
                        type: 'error',
                        message: '请至少选择一个权限点'
                    })
                } else {
                    this.activeStep++
                    // 在第三步回填已选择的权限数据
                    this.$refs.diabledTree.forEach((tree, index) => {
                        tree.setCheckedKeys(this.roleForm.perms[index])
                    })
                }
            }
        },

        // 获取权限树形数据
        async getTreeList() {
            const res = await getTreeListAPI()
            this.treeList = res.data
            // 深拷贝数据用于第三步展示
            this.disableTreeList = JSON.parse(JSON.stringify(res.data))
            // 处理展示用的树形数据，添加禁用状态
            addDisabled(this.disableTreeList)
        },

        // 确认添加/修改角色
        async confirmAdd() {
            if (this.roleId) {
                // 编辑模式：调用更新接口
                await updateRoleAPI(this.roleForm)
            } else {
                // 新增模式：调用创建接口
                await createRoleUserAPI(this.roleForm)
            }
            // 提示操作成功
            this.$message({
                type: 'success',
                message: `${this.roleId ? '编辑' : '新增'}角色成功`
            })
            // 返回上一页
            this.$router.back()
        }
    }
}
</script>

<style scoped lang="scss">
::v-deep .el-tree-node__content label.el-checkbox.is-checked {
    span.is-checked .el-checkbox__inner {
        background-color: #0094ff;
    }
}

.my-disabled {
    color: rgba(0, 0, 0, 0.3);
}

.add-role {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
        display: flex;
        justify-content: space-between;
        padding: 0 20px;
        height: 64px;
        line-height: 64px;
        font-size: 16px;
        font-weight: bold;
        background-color: #fff;

        .left {
            span {
                margin-right: 4px;
            }

            .arrow {
                cursor: pointer;
            }
        }

        .right {
            text-align: right;
        }
    }

    .add-main {
        position: fixed;
        top: 64px;
        bottom: 88px;
        width: 100%;
        overflow-y: auto;
        background: #f4f6f8;
        padding: 20px 230px;
        display: flex;

        .step-container {
            height: 400px;
            width: 200px;
        }

        .form-container {
            flex: 1;
            background-color: #fff;
            overflow-y: auto;

            .title {
                height: 60px;
                line-height: 60px;
                padding-left: 20px;
            }

            .form {
                margin-bottom: 20px;
                padding: 20px 65px 24px;

                .el-form {
                    display: flex;
                    flex-wrap: wrap;
                }

                .info {
                    font-size: 14px;
                    color: #666;

                    .form-item {
                        margin-bottom: 20px;
                    }
                }
            }

            .form-box {
                width: 600px;
                display: flex;
                flex-direction: column;
            }
        }
    }

    .add-footer {
        position: fixed;
        bottom: 0;
        width: 100%;
        padding: 24px 50px;
        color: #000000d9;
        font-size: 14px;
        background: #fff;
        text-align: center;
        z-index: 10001;
    }

    .tree-wrapper {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;

        .tree-item {
            flex: 1;
            padding: 0px 4px;
            text-align: center;

            .tree-title {
                background: #f5f7fa;
                text-align: center;
                padding: 10px 0;
                margin-bottom: 12px;
            }
        }
    }
}
</style>